package com.liao.cloudstorage.controller;


import com.liao.cloudstorage.entity.Key;
import com.liao.cloudstorage.entity.User;
import com.liao.cloudstorage.service.IKeyService;
import com.liao.cloudstorage.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author liao
 * @since 2019-04-22
 */
@Controller
public class UserController {
    @Autowired
    private IUserService userService;

    @GetMapping("/")
    public String index() {
        return "index";
    }


    @GetMapping("/user/change")
    public String changeInfo() {
        return "changeInfo";
    }

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @PostMapping("/login")
    public String login(HttpSession session, String username, String password, ModelMap modelMap) {

        User admin = userService.findUserByUserNameAndPassWord(username, password);
        if (admin != null) {
            session.setAttribute("user", admin);
            return "redirect:/";
        } else {
            modelMap.addAttribute("code", -1);
            modelMap.addAttribute("info", "用户名或者密码错误");
            return "login";
        }

    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        return "redirect:/login/";
    }

    @Autowired
    private IKeyService keyService;

    @GetMapping("/user/token")
    public String getToken(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        Key key = keyService.getKeyByUserId(user.getId());

        model.addAttribute("user", user);
        model.addAttribute("key", key);

        return "token";

    }
    @GetMapping("/gltf")
    public String testGltf(){
        return "gltf/index";
    }

}
